﻿
Imports System.Net
Imports idcommon
Imports idcommon.uskResponse

Public Class idcontext
    Public Shared timeoutMS As Int64 = 0
    Private Shared IDCONTEXT_USRK_TIMEMS As Int64 = 0
    Private _serverUrl As String = Nothing
    Private _id As String = Nothing
    Private _userSiteRandomKey As String = Nothing
    Private _loggedIn As Boolean = False
    Private _httpCtx As httpContext = Nothing
    Private _sitekey As String = Nothing

    Shared Sub New()
        assert(strstartwith(usrkPathIdentity, network.pathSeperator))
        assert(strstartwith(loginPathIdentity, network.pathSeperator))
        IDCONTEXT_USRK_TIMEMS = counter.registerAverageAndLastAverage("IDCONTEXT_USRK_TIMEMS")
        timeoutMS = secondsToMilliseconds(10)
    End Sub

    Private Function uskUrl() As String
        If _id Is Nothing Then
            Return _serverUrl + usrkPathIdentity
        Else
            Return urlUtils.appendQuery(_serverUrl + usrkPathIdentity, _
                                        query.id, _id, _
                                        query.host, _httpCtx.url().host())
        End If
    End Function

    Private Sub _login()
        Dim startticks As Int64 = 0
        startticks = Now.Ticks()
        Dim response As HttpWebResponse = Nothing
        If requestHttpWeb(uskUrl(), response, timeoutMS:=timeoutMS) Then
            If response.StatusCode = statusCode.success Then
                _loggedIn = readHttpResponse(response, _sitekey, uskUrl())
                If Not _loggedIn Then
                    raiseError(errorHandle.errorType.warning, "idsystem responsed success, but no content.")
                Else
                    _loggedIn = strsame(_sitekey, _userSiteRandomKey)
                End If
            Else
                response.Close()
                Select Case response.StatusCode
                    Case statusCode.noIdInput
                        raiseError(errorHandle.errorType.warning, _
                                   "idsystem responded noIdInput, ", response.StatusDescription, _
                                   ", protocol changed.")
                    Case statusCode.noHostInput
                        raiseError(errorHandle.errorType.warning, _
                                   "idsystem responded noHostInput, ", response.StatusDescription, _
                                   ", protocol changed.")
                    Case statusCode.notfound
                        raiseError(errorHandle.errorType.information, _
                                   "idsystem responded notfound, ", response.StatusDescription)
                    Case statusCode.noValidIp
                        raiseError(errorHandle.errorType.warning, _
                                   "idsystem reponded noValidIp, ", response.StatusDescription, _
                                   ", check network status.")
                    Case Else
                        raiseError(errorHandle.errorType.warning, _
                                   "idsystem responsed an unknown status code, ", response.StatusCode, ", ", _
                                   response.StatusDescription, ", protocol changed.")
                End Select
                _loggedIn = False
            End If
        Else
            raiseError(errorHandle.errorType.warning, _
                       "cannot connected to idsystem, url ", uskUrl())
            _loggedIn = False
        End If
        counter.increase(IDCONTEXT_USRK_TIMEMS, ticksToMilliseconds(Now.Ticks() - startticks))
    End Sub

    Public Function login() As Boolean
        If Not _loggedIn Then
            _login()
        End If
        Return _loggedIn
    End Function

    Public Function loggedIn() As Boolean
        Return _loggedIn
    End Function

    Public Function id() As String
        Return copy(_id)
    End Function

    Public Function sitekey() As String
        Return copy(_sitekey)
    End Function

    Public Function loginUrl() As String
        Dim returnUrl As String = Nothing
        If Not _httpCtx Is Nothing Then
            returnUrl = _httpCtx.url().full()
        End If
        Return urlUtils.appendQuery(_serverUrl + loginPathIdentity, query.id, _id, query.returnUrl, returnUrl)
    End Function

    Public Function forceUpdateLoginUrl() As String
        Dim rtn As String = Nothing
        rtn = loginUrl()
        Return urlUtils.appendQuery(rtn, query.forceUpdate, "1")
    End Function

    Public Sub New(ByVal serverUrl As String, _
                   ByVal id As String, _
                   ByVal userSiteRandomKey As String, _
                   ByVal context As httpContext, _
                   Optional ByVal autologin As Boolean = True)
        kickRight(serverUrl, network.pathSeperator)
        copy(_serverUrl, serverUrl)
        copy(_id, id)
        copy(_userSiteRandomKey, userSiteRandomKey)
        _httpCtx = context
        If autologin Then
            _login()
        End If
    End Sub

    Public Sub New(ByVal id As String, ByVal userSiteRandomKey As String, ByVal context As httpContext, _
                   Optional ByVal autologin As Boolean = True)
        Me.New(defaultServerUrl, id, userSiteRandomKey, context, autologin)
    End Sub
End Class
